<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      :title="!dataForm.id ? $t('add') : $t('update')"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="50%"
      top="70px"
    >
      <div class="dialogInner">
        <el-form
          :model="dataForm"
          :rules="dataRule"
          ref="dataForm"
          @keyup.enter.native="dataFormSubmitHandle()"
          :label-width="$i18n.locale === 'en-US' ? '140px' : '130px'"
          :disabled="disabled"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="场馆名称" prop="ismapId">
                <el-select
                  v-model="dataForm.ismapId"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in optionsdata"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场馆类型" prop="venuesType">
                <ren-select
                  v-model="dataForm.venuesType"
                  dict-type="venuesType"
                  placeholder="请选择场馆类型"
                  style="width: 100%"
                ></ren-select>
                <!--<SelectComponent-->
                <!--dictType="venuesType"-->
                <!--v-model="dataForm.venuesType"-->
                <!--placeholder="类型"-->
                <!--&gt;-->
                <!--</SelectComponent>-->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经纬度" prop="lonandLat">
                <el-input
                  v-model="dataForm.lonandLat"
                  style="width: 60%; margin-right: 10px"
                ></el-input>
                <el-button type="primary" size="mini" @click="mapCli()"
                  >地图选点</el-button
                >
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="开放时间" prop="openingHours">
                <el-input
                  v-model="dataForm.openingHours"
                  placeholder="开放时间"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场馆标签" prop="venuesDescribe">
                <el-input
                  v-model="dataForm.venuesDescribe"
                  placeholder="场馆标签"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="场馆电话" prop="venuesPhone">
                <el-input
                  v-model="dataForm.venuesPhone"
                  placeholder="场馆电话"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="可预约时间(上午)"
                prop="reservationMorningTime"
              >
                <el-input
                  v-model="dataForm.reservationMorningTime"
                  placeholder="可预约时间(上午)"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="可预约时间(下午)"
                prop="reservationAfterTime"
              >
                <el-input
                  v-model="dataForm.reservationAfterTime"
                  placeholder="可预约时间(下午)"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="场馆地址" prop="address">
                <el-input
                  v-model="dataForm.address"
                  placeholder="场馆地址"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="场馆介绍" prop="venuesIntroduce">
                <el-input
                  v-model="dataForm.venuesIntroduce"
                  placeholder="场馆介绍"
                  type="textarea"
                  :rows="5"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <p class="pdl60">
                <span class="red">*</span>场馆封面图<span
                  >(支持png、jpg，建议尺寸750*380px，最多1张)</span
                >
              </p>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="appearancePic">
                <el-upload
                  class="avatar-uploader"
                  :action="url"
                  :show-file-list="false"
                  :on-success="
                    (res, file, fileList) => successHandle1(res, file, fileList)
                  "
                  :before-upload="
                    (file) => beforeUploadHandle(file, 'appearancePic')
                  "
                >
                  <img
                    v-if="dataForm.appearancePic"
                    :src="dataForm.appearancePic"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <p class="pdl60">
                场馆详情图<span
                  >(支持png、jpg，建议尺寸750*380px，最多10张)</span
                >
              </p>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" prop="">
                <el-upload
                  :preview-src-list="dataForm.picList"
                  :action="url"
                  :file-list="fileListtwo"
                  :limit="10"
                  :before-upload="(file) => beforeUploadHandle(file, 'picList')"
                  list-type="picture-card"
                  :on-success="successHandletwo"
                  :on-remove="handleRemovetwo"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!--地图-->
      <template slot="footer" v-if="!disabled">
        <el-button @click="resetForm">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()"
          >{{ $t("confirm") }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      width="80%"
      :visible.sync="mapShow"
      title="地图选点"
      top="70px"
      :showClose="false"
    >
      <mapdiv
        ref="mapDiv"
        style="width: 96%; margin: 0 auto 20px"
        :longitude="dataForm.longitude"
        :latitude="dataForm.latitude"
        @getPos="getPosVal($event)"
      >
      </mapdiv>
    </el-dialog>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </div>
</template>

<script>
import mapdiv from "./map2";
import Cookies from "js-cookie";

export default {
  components: {
    mapdiv,
  },
  data() {
    return {
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
      optionsdata: [],
      mapShow: false,
      dialogImageUrl: "",
      dialogVisible: false,
      dialogImageUrltwo: "",
      dialogVisibletwo: false,
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      fileList: [],
      fileListtwo: [],
      options: [
        {
          dictValue: 101,
          dictLabel: "博物馆",
        },
        {
          dictValue: 102,
          dictLabel: "文化馆",
        },
        {
          dictValue: 103,
          dictLabel: "大剧院",
        },
      ],
      dataRule: {
        address: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        venuesIntroduce: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        appearancePic: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        openingHours: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        ismapId: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        lonandLat: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "blur",
          },
        ],
        venuesType: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
      },
      visible: false,
      dataForm: {
        id: "",
        ismapId: "",
        longitude: "",
        latitude: "",
        picList: [],
        appearancePic: "",
        venuesIntroduce: "",
        address: "",
        reservationMorningTime: "",
        reservationAfterTime: "",
        venuesDescribe: "",
        venuesPhone: "",
        openingHours: "",
        venuesType: "",
        lonandLat: "",
      },
    };
  },
  computed: {},
  mounted() {
    //DOM初始化完成进行地图初始化
    this.getcgdata();
  },
  // beforeDestroy() {
  //   if (!this.map) {
  //     return;
  //   }
  //   this.map.destroy();
  //   this.map = null;
  // },
  watch: {
    "dataForm.ismapId"(newval, oldval) {
      if (newval != oldval) {
        let obj = this.optionsdata.filter((item) => item.id == newval);
        if (obj[0]) {
          this.dataForm.venuesIntroduce = obj[0].info||this.dataForm.venuesIntroduce;
          this.dataForm.address = obj[0].address||this.dataForm.venuesIntroduce;
          this.dataForm.latitude = obj[0].latitude;
          this.dataForm.longitude = obj[0].longitude;
          this.dataForm.lonandLat = obj[0].longitude + "," + obj[0].latitude;
        }
      }
    },
  },
  methods: {
    getcgdata() {
      this.$http
        .get("sys/ismap/pageNoPro", {
          params: {
            page: 1,
            limit: -1,
            type: 7,
          },
        })
        .then((res) => {
          if (res.data.code == 0) {
            this.optionsdata = res.data.data.list;
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },

    mapCli() {
      this.mapShow = true;
      this.$nextTick(() => {
        this.$refs.mapDiv.initMap();
      });
    },
    getPosVal(obj) {
      this.mapShow = false;
      this.dataForm.latitude = obj.lat;
      this.dataForm.longitude = obj.lon;
      this.dataForm.lonandLat = obj.lon + "," + obj.lat;
    },
    // 上传之前
    beforeUploadHandle(file, name) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },

    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            if (this.cropperIndex == "appearancePic") {
              //封面照
              this.successHandle1(res.data);
            } else {
              //详情照片
              this.successHandletwo(res.data);
            }
          }
        });
      }
    },
    // 上传成功
    successHandle1(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.appearancePic = res.data.url;
    },
    handleRemovetwo(file, fileList) {
      if (fileList.length == 0) {
        this.dataForm.picList = [];
      } else {
        this.fileListtwo = fileList;
        this.dataForm.picList = fileList.map((item) => {
          return item.url;
        });
      }
    },
    // 上传成功
    successHandletwo(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.fileListtwo.unshift({
        name: "",
        url: res.data.url,
      });
      this.dataForm.picList = this.fileListtwo.map((item) => {
        return item.url;
      });
    },
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.fileListtwo=[];
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.fileList = [];
      this.$http
        .get("/travel/culturalvenues/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data,
          };
          this.dataForm.lonandLat =
            this.dataForm.longitude + "," + this.dataForm.latitude;
          if (this.dataForm.appearancePic) {
            this.fileList = [
              {
                name: "",
                url: this.dataForm.appearancePic,
              },
            ];
          } else {
            this.fileList = [];
          }

          if (this.dataForm.picList) {
            let lsdata = this.dataForm.picList;
            this.fileListtwo = lsdata.map((item, index, arr) => {
              let json = {};
              json.name = "";
              json.url = item;
              return json;
            });
          } else {
            this.fileListtwo = [];
          }
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle(formName) {
      // this.dataForm.picList=null;

      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$http[!this.dataForm.id ? "post" : "put"](
            "/travel/culturalvenues",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.fileList = [];
              this.fileListtwo = [];
              this.dataForm = {
                id: "",
                name: "",
                longitude: "",
                latitude: "",
                picList: [],
                appearancePic: "",
                venuesIntroduce: "",
                address: "",
                reservationMorningTime: "",
                reservationAfterTime: "",
                venuesDescribe: "",
                venuesPhone: "",
                openingHours: "",
                venuesType: "",
                lonandLat: "",
              };
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.visible = false;
    },
  },
  props: {
    disabled: Boolean,
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 400px;
  position: relative;
}

.Addresssearch {
  position: absolute;
  top: 10px;
  left: 20px;
  height: 50px;
  width: 900px;
  z-index: 88;
  background: #fff;
  padding: 5px 0 0 10px;
}
.red {
  color: #f44;
  margin-right: 4px;
}
</style>
